import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
import { Pokemon } from "../pokemon.type";

export const pokemonApi = createApi({
  baseQuery: fetchBaseQuery({
    baseUrl: "https://pokeapi.co/api/v2/",
    // 修改请求信息用的，没啥大用
    fetchFn: (input, init) => {
      console.log("fetchFn", input, init);
      return fetch(input, init);
    },
  }),
  tagTypes: ["Pokemon"],
  endpoints: (builders) => ({
    // builder.query<返回类型, query接受的类型>
    getPokemonByName: builders.query<Pokemon, string>({
      query: (name) => ({
        url: `pokemon/${name}`,
        validateStatus: (res, body) => {
          console.log("valid:", res, body);
          // 如果是非法请求，通过res.status区分是否是error, 但是error信息为空
          return !(res.status >= 400);
        },
      }),
      // 类似以前的QueryKey,用于存储数据
      providesTags: (result, error, arg) => {
        console.log("providesTags:", result, error, arg);
        return [{ type: "Pokemon", arg }];
      },
      transformResponse: (res: any) => {
        console.log("response:", res);
        return {
          name: res?.name || "",
          img: res.sprites?.front_default || "",
        };
      },
    }),
    // mutation
    updatePokemonName: builders.mutation<Pokemon, Partial<Pokemon>>({
      query: ({ name, ...patch }) => ({
        url: `patch`,
        method: `PATCH`,
        body: patch,
      }),
      // 和query的providesTags参数一样，只是指定要invalide的数据可以
      invalidatesTags: (result, error, arg) => [{ type: "Pokemon", arg }],
      // 可用于乐观更新
      onQueryStarted(arg, api) {
        const { name, img } = arg;
        const { dispatch, queryFulfilled } = api;
        const patchResult = dispatch(
          pokemonApi.util.updateQueryData(
            "getPokemonByName",
            name || "",
            (draft) => {
              // 直接mutate当前缓存的对象
              Object.assign(draft, { name, img });
            }
          )
        );
        // 乐观更新失败则undo
        /*try {
          await queryFulfilled;
        }catch (e) {
          patchResult.undo();
        }*/
        queryFulfilled.catch(patchResult.undo);
      },
    }),
  }),
});

export const { useGetPokemonByNameQuery, useUpdatePokemonNameMutation } =
  pokemonApi;

// updatePokemon即触发mutation的函数
/*const [updatePokemon, { isLoading }] = useUpdatePokemonNameMutation();*/
